########################################################################################
##  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING THIS SOFTWARE
##
##  By downloading, copying, installing or using the software you agree to this license.
##  If you do not agree to this license, do not download, install, copy or use the software.
##
## Copyright (C) 2013, AerVision Technologies Pty Ltd, all rights reserved.
##
## Redistribution and use in source and binary forms, with or without modification,
## are permitted provided that the following conditions are met:
##
##   * Redistribution's of source code must retain the above copyright notice,
##     this list of conditions and the following disclaimer.
##
##   * Redistribution's in binary form must reproduce the above copyright notice,
##     this list of conditions and the following disclaimer in the documentation
##     and/or other materials provided with the distribution.
##
##   * The name of AerVision Technologies, may not be used to endorse or promote products
##     derived from this software without specific prior written permission.
##
## This software is provided by the copyright holders and contributors to demonstrate 
## www.AerCloud.net Framework as a Service API (FaaS), "as is" and
## any express or implied warranties, including, but not limited to, the implied
## warranties of merchantability and fitness for a particular purpose are disclaimed.
## In no event shall the copyright holder or contributors be liable for any direct,
## indirect, incidental, special, exemplary, or consequential damages
## (including, but not limited to, procurement of substitute goods or services;
## loss of use, data, or profits; or business interruption) however caused
## and on any theory of liability, whether in contract, strict liability,
## or tort (including negligence or otherwise) arising in any way out of
## the use of this software, even if advised of the possibility of such damage.
########################################################################################

import time
import thread
import base64

from logging import getLogger

from suds.client import Client
from suds import WebFault

from aercloudclient.utils.NameCache import NameCache
from aercloudclient.utils.ImageCache import ImageCache
from aercloudclient.utils.Settings import Settings
from aercloudclient.utils.ImageData import ImageData
from aercloudclient.utils.ImageUtils import ImageUtils

logging = getLogger(__name__)

class AerCloudNet_Interface():
    AerCloud_net = None
    IsAccessKeyValid = None
        
    @staticmethod
    def Connect():
        #url = 'https://www.aercloud.net/webapi?wsdl'
        url = 'https://www.aercloud.net/webapi?singleWsdl'
        error_count = 0
        while True:
            try:
                client = Client(url, faults=True)
                logging.debug(client)
                AerCloudNet_Interface.AerCloud_net = client.service
                AerCloudNet_Interface.IsAccessKeyValid = False
                AerCloudNet_Interface.AerCloud_net.query(None, None)
                break
            except Exception, ex:
                error_count += 1
                if error_count > 3:
                    logging.error(ex)
                    raise
            time.sleep(1)
    
    @staticmethod
    def InitConnection(mainWindow):
        def connect():
            try:
                AerCloudNet_Interface.Connect()
                logging.info("Connection to remote server is OK.")
                if Settings.Default.AccessKey == None or Settings.Default.AccessKey == "":
                    logging.info("Access key is required")
                    return
                logging.info("Sending a test query using provided access key. Text is 'HELLO'...")
                try:
                    s = AerCloudNet_Interface.AerCloud_net.query(Settings.Default.AccessKey, "HELLO")
                    logging.info("Received reply '" + s)
                    logging.info("Excellent! everything works fine.")
                    AerCloudNet_Interface.IsAccessKeyValid = True
                except WebFault, wex:
                    logging.error("Server Error> Received for provided access key: " + wex.fault.faultstring)
            except Exception, ex:
                logging.error("Connecting failed. " + str(ex))
        if Settings.Default.AccessKey == None or Settings.Default.AccessKey == "":
            Settings.Default.AccessKey = ""
        logging.info("Connecting to the remote server...")
        AerCloudNet_Interface.AccessKey = Settings.Default.AccessKey
        thread.start_new_thread(connect, ())

    @staticmethod
    def GetImageNames(personName):
        # TODO: NameCache
        try:
            logging.info("AerCloud.net call> Retrieving list of saved images from server...")
            result = AerCloudNet_Interface.AerCloud_net.get_image_names(AerCloudNet_Interface.AccessKey, personName)
            if result == "":
                return []
            else:
                return result.string
        except WebFault, wex:
                logging.error("AerCloud.net ERROR> " + wex.fault.faultstring)                            
        except Exception, ex:
                logging.error("ERROR> " + str(ex))
        return []

    @staticmethod
    def SaveImage(personName, imageName, data):
        try:
            """ FIXME:
            result = AerCloudNet_Interface.AerCloud_net.detect(Settings.Default.AccessKey, "face", data.format, data.asBase64())
            if result == "":
                logging.info("[" + imageName + "] " + "There is no face present in this image");
                return None
            elif len(result.detected_object) == 1:
                logging.info("[" + imageName + "] " + "One face detected");            
            else:
                logging.info("[" + imageName + "] " + "There is more than one face present in this image, the biggest face is saved");
            """
            logging.info("AerCloud.net call> [" + personName + " - " + imageName + "] Saving face")
            if AerCloudNet_Interface.AerCloud_net.save_image(Settings.Default.AccessKey, "face", data.format, data.asBase64(), personName, imageName, True):
                logging.info("[" + personName + " - " + imageName + "] " + "Save successful")
            else:
                logging.info("[" + personName + " - " + imageName + "] + " + "Save failed")
            ImageCache.Delete(personName, imageName)
            NameCache.AddImageName(personName, imageName)
            return True
        except WebFault, wex:
            logging.error("AerCloud.net ERROR> [" + imageName + "] " + wex.fault.faultstring)            
        except Exception, ex:
            logging.error("ERROR> [" + imageName + "] " + str(ex))
        return False
    
    @staticmethod
    def GetNames():
        logging.info("AerCloud.net call> Retrieving list of names from server...")
        result = AerCloudNet_Interface.AerCloud_net.get_names(Settings.Default.AccessKey)
        if result == "":
            return []
        else:
            return result.string
            
    @staticmethod
    def GetImage(personName, imageName):
        try:
            data = ImageCache.Get(personName, imageName)
            if data == None:
                logging.info("AerCloud.net call> [" + personName + " - " + imageName + "] Retrieving face image...")
                face_image = AerCloudNet_Interface.AerCloud_net.get_image_png(Settings.Default.AccessKey, personName, imageName)
                data = ImageData(data=face_image)
                ImageCache.Put(personName, imageName, data)
            return data
        except WebFault, wex:
            logging.error("AerCloud.net ERROR> [" + imageName + "] " + wex.fault.faultstring)
        except Exception, ex:
            logging.error("ERROR> [" + imageName + "] " + str(ex))
            
        return None
    
    @staticmethod
    def DeleteName(personName):
        try:
            logging.info("AerCloud.net call> Delete name " + "[" + personName + "]")
            AerCloudNet_Interface.AerCloud_net.delete_images(Settings.Default.AccessKey, personName)
            ImageCache.Delete(personName);
            return True
        except WebFault, wex:
            logging.error("AerCloud.net ERROR> [" + personName + "] " + wex.fault.faultstring)
        except Exception, ex:
            logging.error("ERROR> [" + personName + "] " + str(ex))
        return False

    @staticmethod
    def DetectFaces(imageName, data):
        try:
            logging.info("AerCloud.net call> Detecting faces " + "[" + imageName + "]...")
            result = AerCloudNet_Interface.AerCloud_net.detect(Settings.Default.AccessKey, "face", data.format, data.asBase64())
            if result == "":
                logging.info("[" + imageName + "] " + "There is no face present in this image");
                return None
            elif len(result.detected_object) == 1:
                logging.info("[" + imageName + "] " + "One face detected");            
            else:
                logging.info("[" + imageName + "] " + str(len(result.detected_object)) + " faces detected");
            faces = []
            for face in result.detected_object:
                faces.append(ImageData(image=ImageUtils.Resize(ImageUtils.CropFace(data.asImage(), face), (128, 128))))
            return faces
        except WebFault, wex:
            logging.error("AerCloud.net ERROR> [" + imageName + "] " + wex.fault.faultstring)
        except Exception, ex:
            logging.error("ERROR> [" + imageName + "] " + str(ex))
            raise
        return []
        
    @staticmethod
    def SearchFace(imageName, imageData):
        try:
            logging.info("AerCloud.net call> Search face " + "[" + imageName + "]")
            result = AerCloudNet_Interface.AerCloud_net.search_by_image(Settings.Default.AccessKey, "face", "png", base64.b64encode(imageData.asPng()), 10000, True)
            logging.info("[" + imageName + "] Search completed")
            results = []
            if result == "":
                return results
            return result.search_result
        except WebFault, wex:
            logging.info("AerCloud.net ERROR> [" + imageName + "] " + wex.fault.faultstring)
        except Exception, ex:
            logging.info("ERROR> [" + imageName + "] " + str(ex))
        return []
        
if __name__ == "__main__":
    pass